package com.jiang.daily.Q966;

import java.util.*;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/09/16 19:29
 */
class Solution {
    // 时间复杂度 O(n2)
    // public String[] spellchecker(String[] wordlist, String[] queries) {
    //     int m = wordlist.length;
    //     int n = queries.length;

    //     String[] vowels = new String[m]; // 将wordlist进行元音处理
    //     for (int i = 0; i < m; i++) {
    //         vowels[i] = replaceVowels(wordlist[i]);
    //     }

    //     String[] query = new String[n]; // 将queries进行元音处理
    //     for (int i = 0; i < n; i++) {
    //         query[i] = replaceVowels(queries[i]);
    //     }

    //     String[] res = new String[n];
    //     Arrays.fill(res, "");

    //     for (int i = 0; i < n; i++) {
    //         // 分为四个等级（1：完全相同、2：大小写问题、3：元音错误、4：无匹配项）
    //         int level = 4;
    //         // 从后向前遍历，因为要返回列表第一个匹配项
    //         for (int j = m - 1; j >=0; j--) {
    //             if (queries[i].equals(wordlist[j])) { // 完全相同, 结束循环
    //                 res[i] = wordlist[j];
    //                 break;
    //             } else if (level >= 2 && queries[i].equalsIgnoreCase(wordlist[j])) { // 等级需大于等于2，大小写问题
    //                 res[i] = wordlist[j];
    //                 level = 2;
    //             } else if (level >= 3 && query[i].equalsIgnoreCase(vowels[j])) { // 等级需大于等于3，元音错误
    //                 res[i] = wordlist[j];
    //                 level = 3;
    //             }
    //         }
    //     }
    //     return res;
    // }


    Set<String> perfect;
    Map<String, String> ingore;
    Map<String, String> vowels;
    public String[] spellchecker(String[] wordlist, String[] queries) {
        perfect = new HashSet<>();
        ingore = new HashMap<>();
        vowels = new HashMap<>();

        for (String word: wordlist) {
            perfect.add(word);

            String ig = word.toLowerCase();
            ingore.putIfAbsent(ig, word);

            String vowel = replaceVowels(ig);
            vowels.putIfAbsent(vowel, word);
        }

        int len = queries.length;
        String[] res = new String[len];
        for (int i = 0; i < len; i++) {
            res[i] = solve(queries[i]);
        }
        return res;
    }

    public String solve(String query) {
        if (perfect.contains(query))
            return query;

        String queryL = query.toLowerCase();
        if (ingore.containsKey(queryL))
            return ingore.get(queryL);

        String queryLV = replaceVowels(queryL);
        if (vowels.containsKey(queryLV))
            return vowels.get(queryLV);

        return "";
    }

    private String replaceVowels(String s) {
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if ("aeiouAEIOU".indexOf(arr[i]) != -1) {
                arr[i] = '.';
            }
        }
        return new String(arr);
    }
}
